package com.ww.java7.monitor;

import java.io.IOException;
import java.nio.file.*;

public class MonitorDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Path path = Paths.get("D:\\");
        path.register(watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);

        while (true) {
            WatchKey watchKey = watchService.take();
            // 获取事件类型
            for (WatchEvent<?> pollEvent : watchKey.pollEvents()) {
                Path context = (Path) pollEvent.context();
                WatchEvent.Kind<?> kind = pollEvent.kind();
                if (kind.name().equals(StandardWatchEventKinds.ENTRY_CREATE.name())) {
                    System.out.println("创建了一个文件：" + context.toString());
                }
                if (kind.name().equals(StandardWatchEventKinds.ENTRY_DELETE.name())) {
                    System.out.println("删除了一个文件：" + context.toString());
                }
                if (kind.name().equals(StandardWatchEventKinds.ENTRY_MODIFY.name())) {
                    System.out.println("修改了一个文件：" + context.toString());
                }
            }

            // 事件处理完毕后要进行reset才能继续监听时间
            watchKey.reset();
        }
    }
}
